package cn.sinata.wanglin.mine.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.xilada.xldutils.activitys.BaseActivity;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.StringUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sinata.wanglin.MainActivity;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.db.dao.UserDao;
import cn.sinata.wanglin.model.LoginInfo;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.ResultData;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

public class AccoutLoginActivity extends BaseActivity {
    @BindView(R.id.et_phone)
    EditText et_phone;//手机号输入框
    @BindView(R.id.et_password)
    EditText et_password;//密码输入框

    @OnClick({R.id.tv_dologin,R.id.iv_forgetpwd,R.id.iv_register,R.id.iv_accoutlogin_delete})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_dologin:
                //描述:登录
                String phone = et_phone.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                if (TextUtils.isEmpty(phone)){
                    showToast("手机号不能为空!");
                    return;
                }
                if (TextUtils.isEmpty(password)){
                    showToast("密码不能为空!");
                    return;
                }
                if(phone.length() != 11|| !StringUtils.isPhoneNumberValid(phone) ){
                    showToast("请输入正确的手机号!");
                    return;
                }

                if(password.length() < 6||password.length()>20){
                    showToast("请输入6-20位密码!");
                    return;
                }
                toLogin(phone,password);
                break;
            case R.id.iv_forgetpwd:
                //描述:忘记密码
                ActivityUtil.create(mContext).go(ForgetPwdActivity.class)
                        .start();
                break;
            case R.id.iv_register:
                //描述:注册新账号
                ActivityUtil.create(mContext).go(RegisterActivity.class)
                        .startForResult(Constant.RET_CODE_DOLOGIN);
                break;
            case R.id.iv_accoutlogin_delete:
                //描述:退出当前页面
                finish();
                break;
        }
    }

    /**
     * 登录接口
     */
    private void toLogin(final String phone, final String password) {
        Observable<ResultData<LoginInfo>> observable = HttpManager.login(phone,password);
        observable.subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showDialog("登录中...");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultDataSubscriber<LoginInfo>(this) {
                    @Override
                    public void onSuccess(String msg, LoginInfo loginInfo) {
//                        showToast(msg);
                        SharedPreferencesUtils.save(Constant.SP_USERID,loginInfo.getId());
                        SharedPreferencesUtils.save(Constant.SP_HOUSING_ID,loginInfo.getHousingID());
                        SharedPreferencesUtils.save(Constant.SP_HOUSING_NAME,loginInfo.getHousingName());
                        SharedPreferencesUtils.save(Constant.SP_PHONE,phone);
                        SharedPreferencesUtils.save(Constant.SP_USER_PWD,password);
                        SharedPreferencesUtils.save(Constant.SP_LOGIN_TYPE,"C");
                        SharedPreferencesUtils.save(Constant.SP_WANGLINID,loginInfo.getAccount());
                        SharedPreferencesUtils.save(Constant.SP_IM_ACCOUNT,loginInfo.getAccount());
                        SharedPreferencesUtils.save(Constant.SP_IM_PWD,loginInfo.getImPassword());
                        SharedPreferencesUtils.save(Constant.SP_HEADURL,loginInfo.getHeadUrl());
                        if(TextUtils.isEmpty(loginInfo.getSex())){
                            SharedPreferencesUtils.save(Constant.SP_SEX,"1");
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_SEX,loginInfo.getSex());
                        }
                        if(TextUtils.isEmpty(loginInfo.getIsforeign())||"0".equals(loginInfo.getIsforeign())){
                            SharedPreferencesUtils.save(Constant.SP_FIND_ME,true);
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_FIND_ME,false);
                        }
                        if(TextUtils.isEmpty(loginInfo.getValid())||"0".equals(loginInfo.getValid())){
                            SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,true);
                        }else{
                            SharedPreferencesUtils.save(Constant.SP_NEED_AUTH,false);
                        }
                        String nick = loginInfo.getNickName();
                        if(TextUtils.isEmpty(nick)){
                            nick = Constant.DEFULT_NICKNAME;
                        }
                        SharedPreferencesUtils.save(Constant.SP_NICKNAME,nick);
                        UserDao.getInstance(mContext).saveUser(loginInfo.getAccount(),nick,loginInfo.getHeadUrl());
                        ActivityUtil.create(mContext).go(MainActivity.class)
                                .start();
                        setResult(RESULT_OK);
                        finish();
                    }
                });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_accout_login);
        ButterKnife.bind(this);
        et_phone.setFocusable(true);
        et_phone.setFocusableInTouchMode(true);
        et_phone.requestFocus();
        InputMethodManager inputManager =
                (InputMethodManager)et_phone.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(et_phone, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==  Constant.RET_CODE_DOLOGIN){
            if (requestCode == Constant.RET_CODE_DOLOGIN){
                if (data!=null){
                    String phone=data.getStringExtra("phone");
                    String password=data.getStringExtra("password");
                    et_phone.setText(phone);
                    et_password.setText(password);
                    toLogin(phone,password);
                }
            }
        }

    }
}
